package netcom;

import java.io.DataInputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

import codeoffloading.CodeOffloadingManager;
import netcom.messages.ExecutionRequestMessage;
import netcom.messages.Message;
import utilities.Constants;
import utilities.SerializableClassUtility;



public class ConnectionThread implements Runnable {

	
	private ServerSocket sockser;
	private Socket sock;
	private boolean run = false;

	
	private int PORT;
	
	
	public ConnectionThread(){
		run = true;
		PORT = Constants.SRV_PORT;
	}
	
	
	
	public void run() {
		
		try {
			sockser = new ServerSocket(PORT);
			
			while(run){
				sock = sockser.accept();
				System.err.println("Connection from"+sock.getInetAddress().toString());
				DataInputStream in = new DataInputStream(sock.getInputStream());
				int len = in.readInt();
				byte[] message = new byte[len]; 
				in.readFully(message);
				if(len > 0){
						Message off = (Message)SerializableClassUtility.getMessaFromBytes(message);
						
						if(off instanceof ExecutionRequestMessage ){
							System.err.println("Execution Request from"+sock.getInetAddress().toString()+", Execution Id: "+off.getMessageId());
							ExecutionRequestMessage off2 = (ExecutionRequestMessage)off;
							CodeOffloadingManager.getInstance().executionRequest(sock, off2);
						}
						
				}else{
					System.err.println("Message length < 1");
				}
				
			}//end while
			
			
			sockser.close();
		} catch (NumberFormatException e) { 
			run = false; e.printStackTrace();
		} catch (IOException e) { 
			run = false; e.printStackTrace();
		}
	}
	
	public boolean isRunning(){ return run; }
	public void stopThread(){ run = false; }
}
